package com.ryskoo.permission.permission.repository;

import com.ryskoo.common.constant.CacheConstant;
import com.ryskoo.framework.core.bean.QueryConditionEnum;
import com.ryskoo.framework.core.bean.QueryMessageDTO;
import com.ryskoo.framework.core.repository.BasicRedisImpl;
import com.ryskoo.framework.core.utils.RedisUtil;
import com.ryskoo.permission.menu.domain.MenuPO;
import com.ryskoo.permission.menu.repository.IMenuRepository;
import com.ryskoo.permission.permission.domain.PermissionPO;
import com.ryskoo.permission.role.domain.RolePO;
import com.ryskoo.permission.role.repository.IRoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.stream.Collectors;

@Primary
@Repository
public class PermissionRedisImpl extends BasicRedisImpl<PermissionPO> implements IPermissionRepository {
	@Autowired
	private RedisUtil redisClient;

	@Autowired
	private IPermissionRepository permissionRepository;
	
	@Autowired
	private IRoleRepository roleRepository;
	
	@Autowired
	private IMenuRepository menuRepository;

	@PostConstruct
	public void init() {
		this.setRedisClient(redisClient);
		this.setDao(permissionRepository);
	}

	public PermissionRedisImpl() {
		super(CacheConstant.PMS_PERMISSION_KEY);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<PermissionPO> getPermissionByRoleId(String roleId) {
		//缓存获取权限
		List<PermissionPO> list = (List<PermissionPO>)redisClient.getSession(CacheConstant.PMS_ROLE_PERMISSIONS_KEY + roleId);
		return list;
	}

	
	/**
	 * 初始化权限,根据角色获取权限列表，放入缓存
	 * 后台管理员和商户登录时，根据登录角色，缓存获取权限
	 * @return
	 */
	@Override
	public void initPermission() {
		//获取角色列表
		List<RolePO> roles = roleRepository.getAll();
		if (roles != null && roles.size() > 0) {
			for (RolePO rolePO : roles) {
				//通过角色获取权限
				 List<PermissionPO> permissionList = permissionRepository.getPermissionByRoleId(rolePO.getUuid());
				 //将角色的权限放入缓存
				 redisClient.setExpireSession(CacheConstant.PMS_ROLE_PERMISSIONS_KEY + rolePO.getUuid(), permissionList, null);
				 
				 //通过角色获取菜单
				 List<MenuPO> menuList = this.getMenuTreeByRoleId(rolePO.getUuid(), rolePO.getType());
				 //将角色关联的菜单放入缓存
				 redisClient.setExpireSession(CacheConstant.PMS_ROLE_MENU_KEY + rolePO.getUuid(), menuList, null);
			}
		}
	}
	
	 /**
     * 根据角色id获取此管理员可见的菜单列表
     * 菜单列表是包含上下级关系的树形结构
     *
     * @param roleId   角色id
     * @param menuType 菜单类型  0：平台菜单  1：商户菜单
     * @return 菜单列表 {@link List}&lt;{@link MenuPO}&gt;
     */
	public List<MenuPO> getMenuTreeByRoleId(String roleId, int menuType) {
        List<MenuPO> menuList = menuRepository.getMenuByRoleId(roleId, menuType);
        List<MenuPO> firstMenus = menuList.stream().filter(item -> StringUtils.isEmpty(item.getParentId())).collect(Collectors.toList());
        for (MenuPO menu : firstMenus) {
            getSubMenus(menu, menuList);
        }
        return firstMenus;
	}
	
    public void getSubMenus(MenuPO menu, List<MenuPO> menuList) {
        List<MenuPO> chilrenList = menuList.stream().filter(item -> item.getParentId().equals(menu.getUuid())).collect(Collectors.toList());
        if (!chilrenList.isEmpty()) {
            menu.setChildrens(chilrenList);
            for (MenuPO chilren : chilrenList) {
                getSubMenus(chilren, menuList);
            }
        } else {
            QueryMessageDTO queryMessage = new QueryMessageDTO();
            queryMessage.addCondition("menuId", QueryConditionEnum.EQ.name(), menu.getUuid());
            menu.setPermissionList(permissionRepository.queryByCondition(queryMessage,false));
        }
    }
}
